package com.black.common.utils.ip;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.log4j.Log4j2;

/**
 * 根据ip获取详细地址
 *
 * @author L
 */
@Log4j2
public class AddressUtils {
    // IP地址查询（太平洋电脑免费）
    public static final String IP_URL = "https://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "XX XX";


    public static String getRealAddressByIP(String ip) {
        String address = UNKNOWN;
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }

        try {
            //https://whois.pconline.com.cn/ipJson.jsp?json=true&ip=113.249.25.54
            String url = IP_URL + "?ip=" + ip + "&json=true";
            //{"ip":"113.249.25.54","pro":"重庆市","proCode":"500000","city":"重庆市","cityCode":"500000","region":"","regionCode":"0","addr":"重庆市 电信","regionNames":"","err":""}
            HttpRequest getRequest = HttpRequest.get(url);

            getRequest.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");

            // 发送请求
            HttpResponse response = getRequest.execute();

            // 打印响应内容
            String respStr = response.body();

            // 转换成json格式(反序列化)   JSON.parse()
            if (StrUtil.isNotBlank(respStr)) {
                //正则表达式去掉\t  \n \r
                respStr = respStr.replaceAll("\\s", "");
                System.out.println(respStr);
                // 解析json数据
                JSONObject json = JSONUtil.parseObj(respStr);
                // c语言拼接字符
                return String.format("%s %s", json.getStr("pro"), json.getStr("city"));
            }
        } catch (Exception e) {
            log.error(e);
        }

        return address;
    }

}
